package com.changzhi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.changzhi.common.constans.Constants;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.BaseUtil;
import com.changzhi.common.util.DateUtil;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.dto.YearDto;
import com.changzhi.ldyl.model.vo.*;
import com.changzhi.mapper.*;
import com.changzhi.service.ActivityService;
import com.changzhi.service.ChatChannelService;
import com.changzhi.service.UserService;
import com.changzhi.service.YearService;
import com.changzhi.util.CommonUtil;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Description:
 * @author: 小落
 * @date: 2020年11月16日
 */
@Slf4j
@Service
public class YearServiceImpl implements YearService {

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ChatChannelService chatChannelService;
	@Resource
	private ActivityLogMapper activityLogMapper;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysDictMapper sysDictMapper;
	@Resource
	private ActivityRecordMapper activityRecordMapper;
	@Resource
	private UserDressUpMapper userDressUpMapper;
	@Resource
	private UserAccountBookMapper userAccountBookMapper;
	private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


	//初始化数据
	public static final List<Map<String,String>> channelList = new ArrayList<>();
	public static final List<Map<String,String>> starList = new ArrayList<>();
	public static final Map<String,String> bossMap = new HashMap<>();
	public static final Map<String,String> externalMap = new HashMap<>();
	public static Map<String,String> externalInfoMap = new HashMap<>();
	public static final List<Integer> giftIdList = new ArrayList<>();

	public final static Integer FAIL = 0;
	public final static Integer WIN = 1;
	public final static Integer TIE = 2;

	/*//初始化
	@PostConstruct
	public void init(){
		//查活动
		redisUtil.del(RedisConstans.ACTIVITY + 3);
		Activity activity = activityService.getActivity(3);
		JSONObject property1 = JSON.parseObject(activity.getProperty1());
		JSONArray property2 = JSON.parseArray(activity.getProperty2());
		//厅数据
		JSONArray channelArr = property1.getJSONArray("channel");
		for (int i = 0; i < channelArr.size(); i++) {
			Map<String,String> channelMap = new HashMap<>();
			channelMap.put("startDate", channelArr.getJSONObject(i).getString("startDate"));
			channelMap.put("endDate", channelArr.getJSONObject(i).getString("endDate"));
			channelMap.put("type", String.valueOf(channelArr.getJSONObject(i).getString("type")));
			channelMap.put("pkStartTime", channelArr.getJSONObject(i).getString("pkStartTime"));
			channelList.add(channelMap);
		}
		//公会数据
		JSONObject external = property1.getJSONObject("external");
		JSONArray list = external.getJSONArray("list");
		for (int i = 0; i < list.size(); i++) {
			JSONArray accountIdList = list.getJSONObject(i).getJSONArray("accountIdList");
			Integer id = list.getJSONObject(i).getInteger("id");
			for (int j = 0; j < accountIdList.size(); j++) {
				ChatChannel channelInfo = getChatChannelInfo(accountIdList.getInteger(j));
				if(channelInfo == null){
					continue;
				}
				externalInfoMap.put("external_channel_" + channelInfo.getChannelId(), String.valueOf(id));
			}
			externalInfoMap.put("external_id_" + id, list.getJSONObject(i).getString("name"));
			externalInfoMap.put("external_icon_" + id, list.getJSONObject(i).getString("icon"));
		}
		externalMap.put("external_start", external.getString("startDate"));
		externalMap.put("external_end", external.getString("endDate"));
		//主播数据
		JSONArray starArr = property1.getJSONArray("star");
		for (int i = 0; i < starArr.size(); i++) {
			Map<String,String> starMap = new HashMap<>();
			starMap.put("startDate", starArr.getJSONObject(i).getString("startDate"));
			starMap.put("endDate", starArr.getJSONObject(i).getString("endDate"));
			starMap.put("type", String.valueOf(starArr.getJSONObject(i).getString("type")));
			starList.add(starMap);
		}
		//老板数据
		JSONObject boss = property1.getJSONObject("boss");
		bossMap.put("boss_start", boss.getString("startDate"));
		bossMap.put("boss_end", boss.getString("endDate"));
		//礼物
		for (int i = 0; i < property2.size(); i++) {
			giftIdList.add(property2.getInteger(i));
		}
		//初始化pk对战厅数据
		initPkList();
	}*/


	@Override
	public void initPkList() {
		for (Map<String, String> map : channelList) {
			String type = map.get("type");
			//今天及今天之前的不在初始化
			LocalDate startDate = LocalDate.parse(map.get("startDate"), dateTimeFormatter);
			if (startDate.isBefore(LocalDate.now()) || startDate.isEqual(LocalDate.now())) {
				log.warn("methodName:initPkList,今天之前的数据不再初始化..，type={},startDate={}",type,startDate);
				continue;
			}
			if("1".equals(type)){
				List<YearRankingVo> list = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL + "_0");
				if(CollectionUtils.isEmpty(list)){
					continue;
				}
				list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(32).collect(Collectors.toList());
				List<YearPkVo> winList = new ArrayList<>();
				for (YearRankingVo yearRankingVo : list) {
					YearPkVo yearPkVo = new YearPkVo();
					BeanUtils.copyProperties(yearRankingVo, yearPkVo);
					winList.add(yearPkVo);
				}
				initPkToCache(winList, type, null);
			} else if( "3".equals(type) || "4".equals(type)){
				List<Map<String,Object>> cacheList = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL_PK + "_" + (Integer.valueOf(type) - 1));
				if(CollectionUtils.isEmpty(cacheList)){
					continue;
				}
				cacheList.sort((Map<String, Object> s1, Map<String, Object> s2) -> (Integer) s1.get("rank") - (Integer) s2.get("rank"));
				List<YearPkVo> winList = new ArrayList<>();
				for (Map<String, Object> pkMap : cacheList) {
					winList.add(getWinChannelId((YearPkVo) pkMap.get("red"), (YearPkVo) pkMap.get("blue")));
				}
				//排序
				List<YearPkVo> sortList = winList.stream().sorted(Comparator .comparing(YearPkVo::getValue).reversed()).collect(Collectors.toList());
				Map<String,Integer> sortMap = new HashMap<>();
				if(!CollectionUtils.isEmpty(sortList)){
					for (YearPkVo yearPkVo : winList) {
						for (int i = 0; i < sortList.size(); i++) {
							if(yearPkVo.getChannelId().equals(sortList.get(i).getChannelId())){
								sortMap.put(yearPkVo.getChannelId(),i);
							}
						}
					}
				}
				initPkToCache(winList, type, sortMap);
			} else if("5".equals(type)){
				List<Map<String,Object>> list = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL_PK + "_" + (Integer.valueOf(type) - 1));
				if(CollectionUtils.isEmpty(list)){
					continue;
				}
				if(list.size() <= 1){
					continue;
				}
				List<YearPkVo> winList = new ArrayList<>();
				YearPkVo redYearPkVo0 = (YearPkVo) list.get(0).get("red");
				YearPkVo blueYearPkVo0 = (YearPkVo) list.get(0).get("blue");
				YearPkVo redYearPkVo1 = (YearPkVo) list.get(1).get("red");
				YearPkVo blueYearPkVo1 = (YearPkVo) list.get(1).get("blue");
				if(redYearPkVo0.getResult() != null){//有一个胜出时排序
					winList.add(getWinChannelId(redYearPkVo0, blueYearPkVo0));
					winList.add(getFailChannelId(redYearPkVo0, blueYearPkVo0));
					winList.add(getFailChannelId(redYearPkVo1, blueYearPkVo1));
					winList.add(getWinChannelId(redYearPkVo1, blueYearPkVo1));
				} else {
					winList.add(getFailChannelId(redYearPkVo1, blueYearPkVo1));
					winList.add(getWinChannelId(redYearPkVo1, blueYearPkVo1));
					winList.add(getWinChannelId(redYearPkVo0, blueYearPkVo0));
					winList.add(getFailChannelId(redYearPkVo0, blueYearPkVo0));
				}
				initPkToCache(winList, type, null);
			}
		}
	}

	private ChatChannel getChatChannelInfo(Integer accountId){
		QueryWrapper<ChatChannel> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(ChatChannel::getOwnerAccountid, accountId);
		wrapper.last("limit 1");
		return chatChannelService.getOne(wrapper);
	}

	@Override
	public void updatePkList(String type, List<Map<String,Object>> paramsList) {
		int i = 1;
		//初始化数据
		for (Map<String, Object> map : paramsList) {
			String red = (String) map.get("red");
			String blue = (String) map.get("blue");
			String sort = (String) map.get("sort");
			String rank = (String) map.get("rank");
			//accountId转换chatChannel
			ChatChannel redChannel = getChatChannelInfo(Integer.valueOf(red));
			if(redChannel == null){
				log.error("===============updatePkList,user 为空");
				break;
			}
			ChatChannel blueChannel = getChatChannelInfo(Integer.valueOf(blue));
			if(blueChannel == null){
				log.error("===============updatePkList,user 为空");
				break;
			}
			YearPkVo redYearPkVo = new YearPkVo();
			redYearPkVo.setAccountId(redChannel.getOwnerAccountid())
					.setChannelId(redChannel.getChannelId())
					.setResultList(new ArrayList<>())
					.setTopStarList(new ArrayList<>())
					.setTopBossList(new ArrayList<>())
					.setValue(0L)
					.setTeam("red")
					.setChannelName(redChannel.getChannelName())
					.setChannelAvatarUrl(redChannel.getAvatarUrl());
			YearPkVo blueYearPkVo = new YearPkVo();
			blueYearPkVo.setAccountId(blueChannel.getOwnerAccountid())
					.setChannelId(blueChannel.getChannelId())
					.setResultList(new ArrayList<>())
					.setTopStarList(new ArrayList<>())
					.setTopBossList(new ArrayList<>())
					.setValue(0L)
					.setTeam("blue")
					.setChannelName(blueChannel.getChannelName())
					.setChannelAvatarUrl(blueChannel.getAvatarUrl());
			String item = CommonUtil.getGroupId(redYearPkVo.getChannelId(), blueYearPkVo.getChannelId());
			redisUtil.hdel(RedisConstans.YEAR_CHANNEL_PK + "_" + type, item);
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put(redYearPkVo.getTeam(), redYearPkVo);
			dataMap.put(blueYearPkVo.getTeam(), blueYearPkVo);
			dataMap.put("pkId", String.valueOf(i));
			dataMap.put("sort", StringUtils.isBlank(sort) ? 0 : Integer.valueOf(sort));
			dataMap.put("rank", StringUtils.isBlank(rank) ? 0 : Integer.valueOf(rank));
			dataMap.put("reChannelId", redChannel.getChannelId());
			redisUtil.hset(RedisConstans.YEAR_CHANNEL_PK + "_" + type, item, dataMap, RedisConstans.ONE_MONTH);
			++i;
		}
	}

	private void initPkToCache(List<YearPkVo> list, String type, Map<String,Integer> sortMap){
		int size = list.size() / 2;
		List<String> itemList = new ArrayList<>();
		for (int i = 0; i < size; i++) {
			Map<String,Object> dataMap = new HashMap<>();
			YearPkVo redYearPkVo = new YearPkVo();
			redYearPkVo.setChannelId(list.get(i).getChannelId())
					.setValue(0L)
					.setResultList(new ArrayList<>())
					.setAccountId(list.get(i).getAccountId())
					.setChannelName(list.get(i).getChannelName())
					.setChannelAvatarUrl(list.get(i).getChannelAvatarUrl())
					.setTopStarList(new ArrayList<>())
					.setTopBossList(new ArrayList<>())
					.setTeam("red");
			YearPkVo blueYearPkVo = new YearPkVo();
			blueYearPkVo.setChannelId(list.get(list.size() - i -1).getChannelId())
					.setValue(0L)
					.setResultList(new ArrayList<>())
					.setAccountId(list.get(list.size() - i -1).getAccountId())
					.setChannelName(list.get(list.size() - i -1).getChannelName())
					.setChannelAvatarUrl(list.get(list.size() - i -1).getChannelAvatarUrl())
					.setTopStarList(new ArrayList<>())
					.setTopBossList(new ArrayList<>())
					.setTeam("blue");
			dataMap.put(redYearPkVo.getTeam(), redYearPkVo);
			dataMap.put(blueYearPkVo.getTeam(), blueYearPkVo);
			dataMap.put("reChannelId", redYearPkVo.getChannelId());
			dataMap.put("rank",i);//rank表示对战双方
			if(sortMap == null){
				dataMap.put("sort", i);//sort表示按照昨日的胜利方战力值排行
			}else{
				Integer sort1 = sortMap.get(list.get(i).getChannelId());
				Integer sort2 = sortMap.get(list.get(list.size() - i - 1).getChannelId());
				if(sort1 != null && sort2 != null){
					dataMap.put("sort", sort1 < sort2 ? sort1 : sort2);
				} else{
					dataMap.put("sort", i);
				}
			}
			//存redis
			String item = CommonUtil.getGroupId(redYearPkVo.getChannelId(), blueYearPkVo.getChannelId());
			Map<String,Object> cacheMap = (Map<String, Object>) redisUtil.hget(RedisConstans.YEAR_CHANNEL_PK + "_" + type, item);
			if(cacheMap == null || cacheMap.get("pkId") == null){
				dataMap.put("createTime", System.currentTimeMillis());
				redisUtil.hset(RedisConstans.YEAR_CHANNEL_PK + "_" + type, item, dataMap, RedisConstans.ONE_MONTH);
				log.warn("methodName:initPkList,初始化数据pktype={}，item={}，成功...,data={}", type, item, dataMap);
			} else{
				log.error("methodName:initPkList,type={}已有pk数据不再初始化...,data={}", type, JSON.toJSONString(dataMap));
			}
			itemList.add(item);
		}
		//删除其他item（差集）
		Set<String> keys = redisUtil.hKeys(RedisConstans.YEAR_CHANNEL_PK + "_" + type);
		if(!CollectionUtils.isEmpty(keys) && !CollectionUtils.isEmpty(itemList)){
			List<String> reduceList = keys.stream().filter(item -> !itemList.contains(item)).collect(toList());
			for (String v : reduceList) {
				redisUtil.hdel(RedisConstans.YEAR_CHANNEL_PK + "_" + type, v);
				log.error("methodName:initPkToCache,type={},删除差集的数据...,data={}", type, JSON.toJSONString(v));
			}
		}
	}


	@Override
	public void doMqDataByPkFinish(String msg) {
		ChatChannelPkGame pkGame = JSON.parseObject(msg, ChatChannelPkGame.class);
		if(pkGame == null){
			return;
		}
		//厅pk
		if (pkGame.getType() != 2) {
			return;
		}
		//获取key并判断是否在指定时间内
		String key = null;
		String type = "";
		for (Map<String, String> map : channelList) {
			if(DateUtil.isBetweenTimeStr(map.get("startDate"), map.get("endDate"), pkGame.getCreateTime())){
				type = map.get("type");
				LocalDateTime pkStartTime = DateUtil.stringToLocalDateTime(map.get("pkStartTime"));
				if(pkGame.getCreateTime().isBefore(pkStartTime)){
					log.warn("当前不属于pk时间段内.....,type={},pkId={},createTime={},pkStartTime={}",type,pkGame.getPkRoundId(),pkGame.getCreateTime().toString(),pkStartTime.toString());
					break;
				}
				key = RedisConstans.YEAR_CHANNEL_PK + "_" + type;
				break;
			}
		}
		if(StringUtils.isBlank(key)){
			return;
		}
		String item = CommonUtil.getGroupId(pkGame.getChannelId(), pkGame.getTargetChannelId());
		YearPkVo redYearPkVo;
		YearPkVo blueYearPkVo;
		List<UserVo> redTopStarList;
		List<UserVo> redTopBossList;
		List<UserVo> blueTopStarList;
		List<UserVo> blueTopBossList;
		List<ChatChannelPkGameUser> redParticipants = !CollectionUtils.isEmpty(pkGame.getParticipants()) ? pkGame.getParticipants() : new ArrayList<>();
		List<ChatChannelPkGameUser> blueParticipants = !CollectionUtils.isEmpty(pkGame.getBlueParticipants()) ? pkGame.getBlueParticipants() : new ArrayList<>();
		List<PkGameBossUserVo> redPkBossUsers = !CollectionUtils.isEmpty(pkGame.getPkBossUsers()) ? pkGame.getPkBossUsers() : new ArrayList<>();
		List<PkGameBossUserVo> bluePkBossUsers = !CollectionUtils.isEmpty(pkGame.getBluePkBossUsers()) ? pkGame.getBluePkBossUsers() : new ArrayList<>();
		//查缓存  双方认证
		Map<String,Object> cache = (Map<String, Object>) redisUtil.hget(key, item);
		if(cache == null){
			log.error("methodName:doMqDataByPkFinish,error=缓存数据不存在！,msg={}", msg);
			return;
		}
		//幂等性判断
		String pkId = (String) redisUtil.hget(RedisConstans.YEAR_PK_ID, pkGame.getPkRoundId());
		if(pkGame.getPkRoundId().equals(pkId)){
			log.error("methodName:doMqDataByPkFinish,error=重复数据！,msg={}", msg);
			return;
		}
		Integer sort = (Integer) cache.get("sort");
		Integer rank = (Integer) cache.get("rank");
		String reChannelId = (String) cache.get("reChannelId");
		//确定红方和蓝方
		redYearPkVo = (YearPkVo) cache.get("red");
		blueYearPkVo = (YearPkVo) cache.get("blue");
		if(!pkGame.getChannelId().equals(redYearPkVo.getChannelId())){
			redYearPkVo = (YearPkVo) cache.get("blue");
			blueYearPkVo = (YearPkVo) cache.get("red");
		}
		List<Integer> redResultList = redYearPkVo.getResultList();
		List<Integer> blueResultList = blueYearPkVo.getResultList();
		//判断是否到了三场
		if(redYearPkVo.getResult() != null){
			log.info("methodName:doMqDataByPkFinish,已得出结果不再记录");
			return;
		}
		//计算分数和谁赢
		redYearPkVo.setValue(redYearPkVo.getValue() + pkGame.getRedTeamScore());
		blueYearPkVo.setValue(blueYearPkVo.getValue() + pkGame.getBlueTeamScore());
		if(pkGame.getRedTeamScore() > pkGame.getBlueTeamScore()){
			redResultList.add(WIN);
			blueResultList.add(FAIL);
		} else if(pkGame.getRedTeamScore() < pkGame.getBlueTeamScore()){
			blueResultList.add(WIN);
			redResultList.add(FAIL);
		} else{
			redResultList.add(TIE);
			blueResultList.add(TIE);
		}
		//计算前三老板和主播
		redTopStarList = redYearPkVo.getTopStarList();
		redTopBossList = redYearPkVo.getTopBossList();
		blueTopStarList = blueYearPkVo.getTopStarList();
		blueTopBossList = blueYearPkVo.getTopBossList();
		//红方主播
		out:for (ChatChannelPkGameUser pkGameUser : redParticipants) {
				for (UserVo userVo : redTopStarList) {
					if(pkGameUser.getUserId().equals(userVo.getUserId())){
						userVo.setValue(pkGameUser.getLovenum() + userVo.getValue()).setNickname(pkGameUser.getNickname()).setAvatarUrl(pkGameUser.getAvatarUrl());
						break out;
					}
				}
				UserVo userVo = new UserVo();
				BeanUtils.copyProperties(pkGameUser, userVo);
				userVo.setValue(pkGameUser.getLovenum());
				redTopStarList.add(userVo);
		}
		redTopStarList = redTopStarList.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(3).collect(
				toList());
		//蓝方主播
		out:for (ChatChannelPkGameUser pkGameUser : blueParticipants) {
				for (UserVo userVo : blueTopStarList) {
					if(pkGameUser.getUserId().equals(userVo.getUserId())){
						userVo.setValue(pkGameUser.getLovenum() + userVo.getValue()).setNickname(pkGameUser.getNickname()).setAvatarUrl(pkGameUser.getAvatarUrl());
						break out;
					}
				}
				UserVo userVo = new UserVo();
				BeanUtils.copyProperties(pkGameUser, userVo);
				userVo.setValue(pkGameUser.getLovenum());
				blueTopStarList.add(userVo);
		}
		blueTopStarList = blueTopStarList.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(3).collect(
				toList());
		//红方老板
		out:for (PkGameBossUserVo gameBossUserVo : redPkBossUsers) {
				for (UserVo userVo : redTopBossList) {
					if(gameBossUserVo.getUserId().equals(userVo.getUserId())){
						userVo.setValue(gameBossUserVo.getValue() + userVo.getValue()).setNickname(gameBossUserVo.getNickname()).setAvatarUrl(gameBossUserVo.getAvatarUrl());
						break out;
					}
				}
				UserVo userVo = new UserVo();
				BeanUtils.copyProperties(gameBossUserVo, userVo);
				userVo.setValue(gameBossUserVo.getValue());
			redTopBossList.add(userVo);
		}
		redTopBossList = redTopBossList.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(3).collect(
				toList());
		//蓝方老板
		out:for (PkGameBossUserVo gameBossUserVo : bluePkBossUsers) {
				for (UserVo userVo : blueTopBossList) {
					if(gameBossUserVo.getUserId().equals(userVo.getUserId())){
						userVo.setValue(gameBossUserVo.getValue() + userVo.getValue()).setNickname(gameBossUserVo.getNickname()).setAvatarUrl(gameBossUserVo.getAvatarUrl());
						break out;
					}
				}
				UserVo userVo = new UserVo();
				BeanUtils.copyProperties(gameBossUserVo, userVo);
				userVo.setValue(gameBossUserVo.getValue());
				blueTopBossList.add(userVo);
		}
		blueTopBossList = blueTopBossList.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(3).collect(
				toList());
		//存值
		redYearPkVo.setTopStarList(redTopStarList);
		redYearPkVo.setTopBossList(redTopBossList);
		blueYearPkVo.setTopStarList(blueTopStarList);
		blueYearPkVo.setTopBossList(blueTopBossList);
		//判断比赛结果
		if(redResultList.size() >= 3){
			int redWinCount = 0;
			int blueWinCount = 0;
			for (Integer count : redResultList) {
				if(count == 1){
					redWinCount++;
				}
			}
			for (Integer count : blueResultList) {
				if(count == 1){
					blueWinCount++;
				}
			}
			if(redWinCount > blueWinCount){
				redYearPkVo.setResult(WIN);
				blueYearPkVo.setResult(FAIL);
			} else if(redWinCount < blueWinCount){
				redYearPkVo.setResult(FAIL);
				blueYearPkVo.setResult(WIN);
			}
		}

		//返回
		Map<String,Object> data = new HashMap();
		if(StringUtils.isNotBlank(reChannelId) && !reChannelId.equals(redYearPkVo.getChannelId())){
			data.put("red",  blueYearPkVo);
			data.put("blue", redYearPkVo);
		}else{
			data.put("red", redYearPkVo);
			data.put("blue", blueYearPkVo);
		}
		data.put("pkId", pkGame.getPkRoundId());
		data.put("reChannelId", reChannelId);
		data.put("sort", sort == null ? 0 : sort);
		data.put("rank", rank);
		redisUtil.hset(key, item, data, RedisConstans.ONE_MONTH);
		redisUtil.hset(RedisConstans.YEAR_PK_ID, pkGame.getPkRoundId(), pkGame.getPkRoundId(), RedisConstans.ONE_MONTH);
		log.info("methodName:doMqDataByPkFinish,完成本次pk记录...，key={}，pkRoundId={}，item={}，data={}",key, pkGame.getPkRoundId(),item,JSON.toJSONString(data));
		//初始化之后的pk数据
		initPkList();
	}

	@Override
	public void doMqDataByUserGift(String msg) {
		UserGift userGift = JSON.parseObject(msg, UserGift.class);
		if(userGift == null){
			return;
		}
		//防重判断
		QueryWrapper<ActivityLog> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(ActivityLog::getActivityId, 3).eq(ActivityLog::getChannelId, userGift.getChannelId()).eq(ActivityLog::getSourceId, userGift.getId());
		ActivityLog activityLog = activityLogMapper.selectOne(wrapper);
		if(activityLog != null){
			log.error("已有该数据！,id={}", userGift.getId());
			return;
		}
		userGift.setCreateTime(LocalDateTime.now());
		//处理排行榜数据
		doRankingsData(userGift);
		//处理公会数据
		doExternalData(userGift);
		//处理老板数据
		doBossData(userGift);
		//处理主播数据
		doStarData(userGift);
		//自动领取领取
		try {
			autoReceiveGift(userGift);
		} catch (Exception e) {
			log.error("methodName:doMqDataByUserGift=============:msg={},error={}",msg,e.getMessage());
			e.printStackTrace();
		}
		//插入日志表
		ActivityLog record = new ActivityLog();
		record.setActivityId(3);
		record.setChannelId(userGift.getChannelId());
		record.setSourceId(userGift.getId());
		activityLogMapper.insert(record);
	}

	//处理排行榜数据
	private void doRankingsData(UserGift userGift){
		//获取key并判断是否在指定时间内
		String key = null;
		for (Map<String, String> map : channelList) {
			if(DateUtil.isBetweenTimeStr(map.get("startDate"), map.get("endDate"), userGift.getCreateTime())){
				key = RedisConstans.YEAR_CHANNEL + "_" + map.get("type");
				break;
			}
		}
		if(StringUtils.isBlank(key)){
			return;
		}
		//查房间信息
		ChatChannel chatChannel = chatChannelService.getChatChannel(userGift.getChannelId());
		if(chatChannel == null){
			return;
		}
		//判断是否为4位数的厅
		if(String.valueOf(chatChannel.getOwnerAccountid()).length() != 4){
			return;
		}
		//战力值计算
		long value = userGift.getTotalGiftValue() * 10;
		YearRankingVo yearRankingVo = (YearRankingVo) redisUtil.hget(key, userGift.getChannelId());
		if(yearRankingVo != null){
			value += yearRankingVo.getValue();
		} else{
			yearRankingVo = new YearRankingVo();
		}
		yearRankingVo.setChannelId(userGift.getChannelId());
		yearRankingVo.setAccountId(chatChannel.getOwnerAccountid());
		yearRankingVo.setValue(value);
		yearRankingVo.setChannelName(chatChannel.getChannelName());
		yearRankingVo.setChannelAvatarUrl(StringUtils.isNotBlank(chatChannel.getAvatarUrl()) ? chatChannel.getAvatarUrl() : Constants.DEFAULT_AVATAR);
		//缓存
		redisUtil.hset(key, userGift.getChannelId(), yearRankingVo, RedisConstans.ONE_MONTH);
	}


	//处理公会数据
	private void doExternalData(UserGift userGift) {
		if(!DateUtil.isBetweenTimeStr(externalMap.get("external_start"), externalMap.get("external_end"), userGift.getCreateTime())){
			return;
		}
		//公会id
		String id = externalInfoMap.get("external_channel_" + userGift.getChannelId());
		if(StringUtils.isBlank(id)){
			return;
		}
		ExternalVo externalVo = (ExternalVo) redisUtil.hget(RedisConstans.YEAR_EXTERNAL, id);
		if(externalVo != null){
			externalVo.setValue(externalVo.getValue() + userGift.getTotalGiftValue() * 10);
		} else{
			externalVo = new ExternalVo();
			externalVo.setId(Integer.valueOf(id));
			externalVo.setValue((long) (userGift.getTotalGiftValue() * 10));
		}
		externalVo.setName(externalInfoMap.get("external_id_" + id));
		redisUtil.hset(RedisConstans.YEAR_EXTERNAL, id, externalVo, RedisConstans.ONE_MONTH);
	}

	//处理老板数据
	private void doBossData(UserGift userGift) {
		if(!DateUtil.isBetweenTimeStr(bossMap.get("boss_start"), bossMap.get("boss_end"), userGift.getCreateTime())){
			return;
		}
		User user = userService.getUser(userGift.getUserId());
		if (user == null) {
			log.error("methodName:doBossData,error=用户数据不存在,user={}", userGift.getUserId());
			return;
		}
		Integer value = userGift.getTotalGiftValue() * 10;
		UserVo userVo = (UserVo) redisUtil.hget(RedisConstans.YEAR_BOSS, user.getUserId());
		if(userVo != null){
			userVo.setValue(userVo.getValue() + value);
		} else{
			userVo = new UserVo();
			userVo.setValue(value);
		}
		userVo.setUserId(userGift.getUserId())
				.setAccountId(user.getAccountId())
				.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
				.setNickname(user.getNickname());
		redisUtil.hset(RedisConstans.YEAR_BOSS, user.getUserId(), userVo, RedisConstans.ONE_MONTH);
		//存礼物值
		redisUtil.zIncrScore(RedisConstans.YEAR_BOSS_VALUE, userGift.getUserId(), Long.valueOf(value), RedisConstans.ONE_MONTH);
	}

	//处理主播数据
	private void doStarData(UserGift userGift) {
		//获取key并判断是否在指定时间内
		String key = null;
		for (Map<String, String> map : starList) {
			if(DateUtil.isBetweenTimeStr(map.get("startDate"), map.get("endDate"), userGift.getCreateTime())){
				key = RedisConstans.YEAR_STAR + "_" + map.get("type");
				break;
			}
		}
		if(StringUtils.isBlank(key)){
			return;
		}


		//存所有主播数据
		Long starValue = (long) userGift.getTotalGiftValue() * 10;
		Long starCache = (Long) redisUtil.hget(RedisConstans.YEAR_STAR_ALL, userGift.getTargetId());
		if(starCache != null){
			starValue = starCache + starValue;
		}
		redisUtil.hset(RedisConstans.YEAR_STAR_ALL, userGift.getTargetId(), starValue, RedisConstans.ONE_MONTH);


		//48进12 和 12进3 主播过滤
		if(key.equals(RedisConstans.YEAR_STAR + "_1")){
			List<String> targetIdList = redisUtil.get(RedisConstans.YEAR_STAR_ID_1);
			if(!CollectionUtils.isEmpty(targetIdList)){
				if(!targetIdList.contains(userGift.getTargetId())){
					//log.info("不属于晋级主播1，targetId={},targetIdList={}", userGift.getTargetId(), targetIdList);
					return;
				}
			}
		}else if(key.equals(RedisConstans.YEAR_STAR + "_2")){
			List<String> targetIdList = redisUtil.get(RedisConstans.YEAR_STAR_ID_2);
			if(!CollectionUtils.isEmpty(targetIdList)){
				if(!targetIdList.contains(userGift.getTargetId())){
					//log.info("不属于晋级主播2，targetId={},targetIdList={}", userGift.getTargetId(), targetIdList);
					return;
				}
			}
		}
		//查房间信息
		User user = userService.getUser(userGift.getTargetId());
		if(user == null){
			log.error("methodName:doStarData,error=用户数据不存在,user={}", userGift.getTargetId());
			return;
		}
		//战力值计算
		long value = userGift.getTotalGiftValue() * 10;
		UserVo userVo = (UserVo) redisUtil.hget(key, userGift.getTargetId());
		if(userVo != null){
			value += userVo.getValue();
		} else{
			userVo = new UserVo();
		}
		userVo.setUserId(user.getUserId())
				.setAccountId(user.getAccountId())
				.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
				.setNickname(user.getNickname())
				.setValue((int) value);
		//缓存
		redisUtil.hset(key, userGift.getTargetId(), userVo, RedisConstans.ONE_MONTH);
	}

	//初始化12强
	@Override
	public void initStartBy12() {
		String key = RedisConstans.YEAR_STAR + "_2";
		List<String> userIdList = redisUtil.get(RedisConstans.YEAR_STAR_ID_2);
		if(!CollectionUtils.isEmpty(userIdList)){
			for (String userId : userIdList) {
				UserVo userVo = (UserVo) redisUtil.hget(key, userId);
				if(userVo == null){
					userVo = new UserVo();
					User user = userService.getUser(userId);
					if (user == null) {
						continue;
					}
					userVo.setUserId(user.getUserId())
							.setAccountId(user.getAccountId())
							.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
							.setNickname(user.getNickname())
							.setValue(0);
					redisUtil.hset(key,userVo.getUserId(),userVo, RedisConstans.ONE_MONTH);
				}
			}
		}
	}


	@Override
	public Object getChannelRankings(YearDto yearDto) {
		if(yearDto.getType() == null || yearDto.getType() <0 || yearDto.getType() > 5){
			throw new ServiceException("类型为空或非法");
		}
		if(yearDto.getType() == 0){
			List<YearRankingVo> cacheList = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL + "_" + yearDto.getType());
			if(CollectionUtils.isEmpty(cacheList)){
				return new PageVo<>();
			}
			cacheList = cacheList.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(50).collect(
					toList());
			return BaseUtil.page(cacheList, yearDto.getPageNo(), yearDto.getPageSize());
		} else {
			List<Map<String,Object>> cacheList = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL_PK + "_" + yearDto.getType());
			if(CollectionUtils.isEmpty(cacheList)){
				if(yearDto.getType() == 1){
					return new PageVo<>();
				}
				return new ArrayList<>();
			}
			List<YearRankingVo> list = new ArrayList<>();
			for (Map<String, Object> map : cacheList) {
				YearPkVo redYearPkVo = (YearPkVo) map.get("red");
				YearPkVo blueYearPkVo = (YearPkVo) map.get("blue");
				if(redYearPkVo.getValue() !=null && redYearPkVo.getValue() != 0){
					YearRankingVo redRankingVo = new YearRankingVo();
					BeanUtils.copyProperties(redYearPkVo, redRankingVo);
					setIcon(redRankingVo);
					list.add(redRankingVo);
				}
				if(blueYearPkVo.getValue() !=null && blueYearPkVo.getValue() != 0){
					YearRankingVo blueRankingVo = new YearRankingVo();
					BeanUtils.copyProperties(blueYearPkVo, blueRankingVo);
					setIcon(blueRankingVo);
					list.add(blueRankingVo);
				}
			}
			list.sort(Comparator.comparing(YearRankingVo::getValue, Comparator.reverseOrder()));
			return BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
		}

	}
/*
	@Override
	public Object getChannelRankings(YearDto yearDto) {
		List<YearRankingVo> list = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL + "_" + yearDto.getType());
		if(CollectionUtils.isEmpty(list)){
			if(yearDto.getType() == 0 || yearDto.getType() == 1){
				return new PageVo<>();
			}
			return new ArrayList<>();
		}
		if(yearDto.getType() == 0){
			list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(50).collect(Collectors.toList());
			return BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
		} else if(yearDto.getType() == 1){
			list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(32).collect(Collectors.toList());
			return BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
		} else if(yearDto.getType() == 2){
			list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(16).collect(Collectors.toList());
			return list;
		} else if(yearDto.getType() == 3){
			list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(8).collect(Collectors.toList());
			return list;
		} else if(yearDto.getType() == 4){
			list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(4).collect(Collectors.toList());
			return list;
		} else if(yearDto.getType() == 5){
			list = list.stream().sorted(Comparator.comparing(YearRankingVo::getValue).reversed()).limit(2).collect(Collectors.toList());
			return list;
		}
		return null;
	}
*/


	//主播 N进48强
	@Override
	public void starPromotionBy48(){
		log.info("methodName:starPromotionBy48,晋级48强主播开始...");
		List<String> userIdList = new ArrayList<>();
		String key = RedisConstans.YEAR_STAR + "_0";
		List<UserVo> list = redisUtil.hGetValuesList(key);
		if(CollectionUtils.isEmpty(list)){
			redisUtil.set(RedisConstans.YEAR_STAR_ID_1,userIdList,RedisConstans.ONE_MONTH);
			log.info("methodName:starPromotionBy48,晋级48强主播结束...");
			return;
		}
		list = list.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(48).collect(toList());
		for (UserVo userVo : list) {
			userIdList.add(userVo.getUserId());
		}
		redisUtil.set(RedisConstans.YEAR_STAR_ID_1,userIdList,RedisConstans.ONE_MONTH);
		log.info("methodName:starPromotionBy48,晋级48强主播结束...，data={}", JSON.toJSONString(userIdList));
	}

	//主播 48进12强
	@Override
	public void starPromotionBy12(){
		log.info("methodName:starPromotionBy12,晋级12强主播开始...");
		List<String> userIdList = new ArrayList<>();
		String key = RedisConstans.YEAR_STAR + "_1";
		List<UserVo> list = redisUtil.hGetValuesList(key);
		if(CollectionUtils.isEmpty(list)){
			redisUtil.set(RedisConstans.YEAR_STAR_ID_2,userIdList,RedisConstans.ONE_MONTH);
			log.info("methodName:starPromotionBy12,晋级12强主播结束...");
			return;
		}
		list = list.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(12).collect(toList());
		for (UserVo userVo : list) {
			userIdList.add(userVo.getUserId());
		}
		redisUtil.set(RedisConstans.YEAR_STAR_ID_2,userIdList,RedisConstans.ONE_MONTH);
		log.info("methodName:starPromotionBy12,晋级12强主播结束...，data={}", JSON.toJSONString(userIdList));
	}

	@Override
	public List<UserVo> topStarList(YearDto yearDto) {
		String key = RedisConstans.YEAR_STAR + "_2";
		List<UserVo> list = redisUtil.hGetValuesList(key);
		if(CollectionUtils.isEmpty(list)){
			return new ArrayList<>();
		}
		list = list.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(10).collect(toList());
		return list;
	}

	@Override
	public List<UserVo> topBossList(YearDto yearDto) {
		Set<Object> userIdSet = redisUtil.zRevRange(RedisConstans.YEAR_BOSS_VALUE, 0, 9);
		List<UserVo> list = redisUtil.hMultiGet(RedisConstans.YEAR_BOSS, userIdSet);
		if(CollectionUtils.isEmpty(list)){
			return new ArrayList<>();
		}
		return list;
	}

	@Override
	public List<ExternalVo> topExternalList(YearDto yearDto) {
		List<ExternalVo> list = redisUtil.hGetValuesList(RedisConstans.YEAR_EXTERNAL);
		if(CollectionUtils.isEmpty(list)){
			return new ArrayList<>();
		}
		for (ExternalVo externalVo : list) {
			externalVo.setIcon(externalInfoMap.get("external_icon_" + externalVo.getId()));
		}
		list = list.stream().sorted(Comparator.comparing(ExternalVo::getValue).reversed()).limit(3).collect(toList());
		return list;
	}

	@Override
	public PageVo<Map<String,Object>> getExternalRankings(YearDto yearDto) {
		List<ExternalVo> list = redisUtil.hGetValuesList(RedisConstans.YEAR_EXTERNAL);
		if(CollectionUtils.isEmpty(list)){
			return new PageVo<>();
		}
		for (ExternalVo externalVo : list) {
			externalVo.setIcon(externalInfoMap.get("external_icon_" + externalVo.getId()));
		}
		list.sort(Comparator.comparing(ExternalVo::getValue, Comparator.reverseOrder()));
		return BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
	}

	@Override
	public Map<String,Object> getBossRankings(YearDto yearDto) {
		Set<Object> userIdSet = redisUtil.zRevRange(RedisConstans.YEAR_BOSS_VALUE, 0, 49);
		List<UserVo> list = redisUtil.hMultiGet(RedisConstans.YEAR_BOSS, userIdSet);
		if(CollectionUtils.isEmpty(list)){
			return new HashMap<>();
		}
		int i = 1;
		int selfRank = -1;
		for (UserVo userVo : list) {
			userVo.setRank(i);
			if(yearDto.getUserId().equals(userVo.getUserId())){
				selfRank = i;
			}
			++i;
		}
		//查询个人信息
		UserVo userVo = (UserVo) redisUtil.hget(RedisConstans.YEAR_BOSS, yearDto.getUserId());
		if(userVo == null){
			userVo = new UserVo();
			User user = userService.getUser(yearDto.getUserId());
			if(user != null){
				userVo.setUserId(user.getUserId())
						.setAccountId(user.getAccountId())
						.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
						.setNickname(user.getNickname())
						.setValue(0)
						.setRank(selfRank);
			}
		}else{
			userVo.setRank(selfRank);
		}
		//返回
		Map<String,Object> map = new HashMap<>();
		map.put("self", userVo);
		PageVo page = BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
		map.put("dataList", page.getDataList());
		map.put("total", page.getTotal());
		return map;
	}

	@Override
	public Object getStarRankings(YearDto yearDto) {
		if(yearDto.getType() == null || yearDto.getType() <0 || yearDto.getType() > 2){
			throw new ServiceException("类型为空或非法");
		}
		String key = RedisConstans.YEAR_STAR + "_" + yearDto.getType();
		List<UserVo> list = redisUtil.hGetValuesList(key);
		if(CollectionUtils.isEmpty(list)){
			return new HashMap<>();
		}
		if(yearDto.getType() == 0){
			list = list.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(60).collect(
					toList());
		} else if(yearDto.getType() == 1){
			list = list.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(48).collect(
					toList());
		} else{
			list = list.stream().sorted(Comparator.comparing(UserVo::getValue).reversed()).limit(12).collect(
					toList());
		}
		int i = 1;
		int selfRank = -1;
		for (UserVo userVo : list) {
			userVo.setRank(i);
			if(yearDto.getUserId().equals(userVo.getUserId())){
				selfRank = i;
			}
			++i;
		}
		//查询个人信息
		UserVo userVo = (UserVo) redisUtil.hget(key, yearDto.getUserId());
		if(userVo == null){
			userVo = new UserVo();
			User user = userService.getUser(yearDto.getUserId());
			if(user != null){
				userVo.setUserId(user.getUserId())
						.setAccountId(user.getAccountId())
						.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
						.setNickname(user.getNickname())
						.setValue(0)
				        .setRank(selfRank);
			}
		}else{
			userVo.setRank(selfRank);
		}
		//返回
		Map<String,Object> map = new HashMap<>();
		map.put("self", userVo);
		PageVo page = BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
		map.put("dataList", page.getDataList());
		map.put("total", page.getTotal());
		return map;
	}

	@Override
	public Map<String, Object> getChannelLockStatus(YearDto yearDto) {
		if(StringUtils.isBlank(yearDto.getChannelId())){
			throw new ServiceException("房间id不能为空");
		}
		ChatChannel chatChannel = chatChannelService.getChatChannel(yearDto.getChannelId());
		if(chatChannel == null){
			throw new ServiceException("房间数据不存在");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("locked", chatChannel.getLockedStatus() == 0 ? false :true);
		return map;
	}

	@Override
	public Map<String, Object> getMemoryData() {
		Map<String, Object> map = new HashMap<>();
		map.put("channelList", channelList);
		map.put("starList", starList);
		map.put("bossMap", bossMap);
		map.put("externalMap", externalMap);
		map.put("externalInfoMap", externalInfoMap);
		return map;
	}

	@Override
	public Object pkList(YearDto yearDto) {
		if(yearDto.getType() == null || yearDto.getType() <0 || yearDto.getType() > 5){
			throw new ServiceException("类型为空或非法");
		}
		List<Map<String,Object>> list = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL_PK + "_" + yearDto.getType());
		if(CollectionUtils.isEmpty(list)){
			if(yearDto.getType() == 1){
				return new PageVo<>();
			}
			return new ArrayList<>();
		}
		for (Map<String, Object> map : list) {
			YearPkVo redYearPkVo = (YearPkVo) map.get("red");
			YearPkVo blueYearPkVo  = (YearPkVo) map.get("blue");
			setIcon(redYearPkVo);
			setIcon(blueYearPkVo);
			//老板主播默认头像
			setDefaultIcon(redYearPkVo.getTopBossList());
			setDefaultIcon(blueYearPkVo.getTopBossList());
			setDefaultIcon(redYearPkVo.getTopStarList());
			setDefaultIcon(blueYearPkVo.getTopStarList());
		}
		//排序
		list.sort((Map<String, Object> s1, Map<String, Object> s2) -> (Integer) s1.get("sort") - (Integer) s2.get("sort"));
		if(yearDto.getType() == 1){
			return BaseUtil.page(list, yearDto.getPageNo(), yearDto.getPageSize());
		} else {
			return list;
		}
	}


	@Override
	public List<YearRankingVo> getTopChannelList() {
		List<YearRankingVo> list = new ArrayList<>();
		List<Map<String,Object>> cacheList = redisUtil.hGetValuesList(RedisConstans.YEAR_CHANNEL_PK + "_5");
		if(CollectionUtils.isEmpty(cacheList)){
			return list;
		}
		cacheList.sort((Map<String, Object> s1, Map<String, Object> s2) -> (Integer) s1.get("rank") - (Integer) s2.get("rank"));
		int i = 0;
		for (Map<String, Object> map : cacheList) {
			YearPkVo redYearPkVo = (YearPkVo) map.get("red");
			YearPkVo blueYearPkVo = (YearPkVo) map.get("blue");
			YearRankingVo redRankingVo = new YearRankingVo();
			YearRankingVo blueRankingVo = new YearRankingVo();
			BeanUtils.copyProperties(redYearPkVo, redRankingVo);
			BeanUtils.copyProperties(blueYearPkVo, blueRankingVo);
			if(i == 0){
				if(redYearPkVo.getResult() != null){
					if(redYearPkVo.getResult() == 1){
						list.add(redRankingVo);
						list.add(blueRankingVo);
					} else {
						list.add(blueRankingVo);
						list.add(redRankingVo);
					}
				}else{
					int redWin = 0;
					int blueWin = 0;
					if(!CollectionUtils.isEmpty(redYearPkVo.getResultList())){
						for (Integer num : redYearPkVo.getResultList()) {
							if(num == 1){
								redWin++;
							}
						}
						for (Integer num : blueYearPkVo.getResultList()) {
							if(num == 1){
								blueWin++;
							}
						}
						if(redWin >= 2){
							list.add(redRankingVo);
							list.add(blueRankingVo);
						} else if(blueWin >= 2){
							list.add(blueRankingVo);
							list.add(redRankingVo);
						}
					}
				}
			} else if(i == 1){
				if(redYearPkVo.getResult() != null){
					if(redYearPkVo.getResult() == 1){
						list.add(redRankingVo);
					} else {
						list.add(blueRankingVo);
					}
				}else{
					int redWin = 0;
					int blueWin = 0;
					if(!CollectionUtils.isEmpty(redYearPkVo.getResultList())){
						for (Integer num : redYearPkVo.getResultList()) {
							if(num == 1){
								redWin++;
							}
						}
						for (Integer num : blueYearPkVo.getResultList()) {
							if(num == 1){
								blueWin++;
							}
						}
						if(redWin >= 2){
							list.add(redRankingVo);
						} else if(blueWin >= 2){
							list.add(blueRankingVo);
						}
					}
				}
			}
			i++;
		}
		if(list.size() != 3){
			return new ArrayList<>();
		}
		for (YearRankingVo yearRankingVo : list) {
			setIcon(yearRankingVo);
		}
		return list;
	}


	private void setIcon(YearPkVo yearPkVo){
		String icon = redisUtil.get(RedisConstans.YEAR_CHANNEL_ICON + "_" + yearPkVo.getAccountId());
		if(StringUtils.isNotBlank(icon)){
			yearPkVo.setChannelAvatarUrl(icon);
		} else if(StringUtils.isBlank(yearPkVo.getChannelAvatarUrl())){
			yearPkVo.setChannelAvatarUrl(Constants.DEFAULT_AVATAR);
		}
	}

	private void setIcon(YearRankingVo yearRankingVo){
		String icon = redisUtil.get(RedisConstans.YEAR_CHANNEL_ICON + "_" + yearRankingVo.getAccountId());
		if(StringUtils.isNotBlank(icon)){
			yearRankingVo.setChannelAvatarUrl(icon);
		} else if(StringUtils.isBlank(yearRankingVo.getChannelAvatarUrl())){
			yearRankingVo.setChannelAvatarUrl(Constants.DEFAULT_AVATAR);
		}
	}


	//获取赢方房间id
	private YearPkVo getWinChannelId(YearPkVo redYearPkVo, YearPkVo blueYearPkVo){
		YearPkVo result = null;
		if(redYearPkVo.getResult() == null){
			List<Integer> redResultList = redYearPkVo.getResultList();
			List<Integer> blueResultList = blueYearPkVo.getResultList();
			if(CollectionUtils.isEmpty(redResultList)){
				result = redYearPkVo;
				return result;
			}
			//提前预判比赛结果
			int redWinCount = 0;
			int blueWinCount = 0;
			for (Integer count : redResultList) {
				if(count == 1){
					++redWinCount;
				}
			}
			for (Integer count : blueResultList) {
				if(count == 1){
					++blueWinCount;
				}
			}
			if(redWinCount >= blueWinCount){
				result = redYearPkVo;
			} else if(redWinCount < blueWinCount){
				result = blueYearPkVo;
			}
		} else{
			if(redYearPkVo.getResult() == 1 ){
				result = redYearPkVo;
			} else if(redYearPkVo.getResult() == 0){
				result = blueYearPkVo;
			} else {
				//胜利场数一致情况下，按照战力值高的算
				if(redYearPkVo.getValue() > blueYearPkVo.getValue()){
					result = redYearPkVo;
				} else if(redYearPkVo.getValue() < blueYearPkVo.getValue()){
					result = blueYearPkVo;
				} else {
					//战力值一致情况下，取红方胜
					result = redYearPkVo;
				}
			}
		}
		return result;
	}

	//获取输方房间id
	private YearPkVo getFailChannelId(YearPkVo redYearPkVo, YearPkVo blueYearPkVo){
		YearPkVo result = null;
		if(redYearPkVo.getResult() == null){
			List<Integer> redResultList = redYearPkVo.getResultList();
			List<Integer> blueResultList = blueYearPkVo.getResultList();
			if(CollectionUtils.isEmpty(redResultList)){
				result = blueYearPkVo;
				return result;
			}
			//提前预判比赛结果
			int redWinCount = 0;
			int blueWinCount = 0;
			for (Integer count : redResultList) {
				if(count == 1){
					++redWinCount;
				}
			}
			for (Integer count : blueResultList) {
				if(count == 1){
					++blueWinCount;
				}
			}
			if(redWinCount >= blueWinCount){
				result = blueYearPkVo;
			} else if(redWinCount < blueWinCount){
				result = redYearPkVo;
			}
		} else{
			if(redYearPkVo.getResult() == 1 ){
				result = blueYearPkVo;
			} else if(redYearPkVo.getResult() == 0){
				result = redYearPkVo;
			} else {
				//胜利场数一致情况下，按照战力值高的算
				if(redYearPkVo.getValue() > blueYearPkVo.getValue()){
					result = blueYearPkVo;
				} else if(redYearPkVo.getValue() < blueYearPkVo.getValue()){
					result = redYearPkVo;
				} else {
					//战力值一致情况下，取红方胜
					result = blueYearPkVo;
				}
			}
		}
		return result;
	}

	//默认头像
	private void setDefaultIcon(List<UserVo> topList){
		if(CollectionUtils.isEmpty(topList)){
			return;
		}
		for (UserVo userVo : topList) {
			if(StringUtils.isBlank(userVo.getAvatarUrl())){
				userVo.setAvatarUrl(Constants.DEFAULT_AVATAR);
			}
		}
	}

	/**
	 * 12.5~12.12赠送达到100000壕气值用户（1000元）可获得蓝海之心头像框
	 * 12.5~12.12赠送达到1000000壕气值的用户（10000元）可获得云火赤兔马座驾
	 * 12.5~12.10收礼达到100000闪耀值的用户（1000元）可获得希望之光头像框
	 * 12.5~12.10收礼达到1000000闪耀值的用户（10000元）可获得兰殇白翼马座驾
	 * 自动领取礼物
	 */
	void autoReceiveGift(UserGift userGift){
		if(userGift == null || userGift.getUserId() ==null){
			return;
		}
		//老板
		UserVo userVo = (UserVo) redisUtil.hget(RedisConstans.YEAR_BOSS, userGift.getUserId());
		if(userVo != null && userVo.getValue() != null){
			Integer id1 = giftIdList.get(0);
			Integer id2 = giftIdList.get(1);
			if(redisUtil.hget(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getUserId(),String.valueOf(id1)) == null && userVo.getValue() >= 100000){
				//是否已领取
				if(!isReceive(userGift.getUserId(),id1)){
					SysDict sysDict = sysDictMapper.selectById(id1);
					receive(userGift.getUserId(), sysDict.getId(), sysDict);
					redisUtil.hset(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getUserId(),String.valueOf(id1),"1", RedisConstans.ONE_MONTH);
				}
			}
			if(redisUtil.hget(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getUserId(),String.valueOf(id2)) == null && userVo.getValue() >= 1000000){
				if(!isReceive(userGift.getUserId(),id2)){
					SysDict sysDict = sysDictMapper.selectById(id2);
					receive(userGift.getUserId(), sysDict.getId(), sysDict);
					redisUtil.hset(RedisConstans.YEAR_CHANNEL_GIFT_USER  + userGift.getUserId(),String.valueOf(id2),"1", RedisConstans.ONE_MONTH);
				}
			}
		}
		//主播
		Integer id3 = giftIdList.get(2);
		Integer id4 = giftIdList.get(3);
		Long sum = (Long) redisUtil.hget(RedisConstans.YEAR_STAR_ALL, userGift.getTargetId());
		if(sum == null){
			sum = 0L;
		}
		/*UserVo userVo0 = (UserVo) redisUtil.hget(RedisConstans.YEAR_STAR+"_0", userGift.getTargetId());
		UserVo userVo1 = (UserVo) redisUtil.hget(RedisConstans.YEAR_STAR+"_1", userGift.getTargetId());
		UserVo userVo2 = (UserVo) redisUtil.hget(RedisConstans.YEAR_STAR+"_2", userGift.getTargetId());
		if(userVo0 != null && userVo0.getValue() != null){
			sum += userVo0.getValue();
		}
		if(userVo1 != null && userVo1.getValue() != null){
			sum += userVo1.getValue();
		}
		if(userVo2 != null && userVo2.getValue() != null){
			sum += userVo2.getValue();
		}*/
		if(sum >= 100000){
			if(redisUtil.hget(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getTargetId(),String.valueOf(id3)) == null && !isReceive(userGift.getTargetId(),id3)){
				SysDict sysDict = sysDictMapper.selectById(id3);
				receive(userGift.getTargetId(), sysDict.getId(), sysDict);
				redisUtil.hset(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getTargetId(),String.valueOf(id3),"1", RedisConstans.ONE_MONTH);
			}
		}
		if(sum >= 1000000){
			if(redisUtil.hget(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getTargetId(),String.valueOf(id4)) == null && !isReceive(userGift.getTargetId(),id4)){
				SysDict sysDict = sysDictMapper.selectById(id4);
				receive(userGift.getTargetId(), sysDict.getId(), sysDict);
				redisUtil.hset(RedisConstans.YEAR_CHANNEL_GIFT_USER + userGift.getTargetId(),String.valueOf(id4),"1", RedisConstans.ONE_MONTH);
			}
		}
	}

	//是否已领取
	private boolean isReceive(String userId, Integer giftId){
		LambdaQueryWrapper<ActivityRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityRecord::getUserId, userId).eq(ActivityRecord::getGiftId, giftId);
		wrapper.last("limit 1");
		ActivityRecord record = activityRecordMapper.selectOne(wrapper);
		if(record != null){
			return true;
		}
		return false;
	}

	/**
	 * 领取并保存礼物和记录
	 * @param userId
	 * @param giftId
	 * @return
	 */
	public void receive(String userId, Integer giftId, SysDict sysDict){
		// 保存装扮礼物数据
		LocalDateTime nowDateTime = LocalDateTime.now();
		UserDressUp dressUp = new UserDressUp();
		dressUp.setUserId(userId);
		dressUp.setType(Integer.valueOf(sysDict.getProperty1()));
		dressUp.setDressId(sysDict.getId());
		dressUp.setPrice(Integer.valueOf(sysDict.getProperty5()));
		dressUp.setStatus(0);
		dressUp.setDuration(StringUtils.isBlank(sysDict.getProperty4()) ? 0 : Integer.valueOf(sysDict.getProperty4()));
		dressUp.setLimitedType(Integer.valueOf(sysDict.getProperty7()));
		dressUp.setCreateTime(nowDateTime);
		dressUp.setUpdateTime(nowDateTime);
		userDressUpMapper.insert(dressUp);
		//保存赠送记录到用户账本表
		UserAccountBook accountBook = new UserAccountBook();
		accountBook.setCurrencyType(6);
		accountBook.setOrderId(String.valueOf(dressUp.getDressId()));
		accountBook.setAccountTitle("双11活动领取");
		accountBook.setReceivingAccount(userId);
		accountBook.setReceivingAmount(0);
		accountBook.setPaymentAccountTotal(0);
		accountBook.setPaymentAccountBalance(0);
		accountBook.setPaymentAmount(0);
		accountBook.setNote("双11活动奖品");
		userAccountBookMapper.insert(accountBook);
		//插入领取记录表
		ActivityRecord record = new ActivityRecord();
		record.setActivityId(3);
		record.setType(1);
		record.setUserId(userId);
		record.setGiftId(giftId);
		activityRecordMapper.insert(record);
	}
}
